﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using THenu.TinyHourseLib.DesignPattern.Abstract_Factory_Pattern;
using THenu.TinyHourseLib.DesignPattern.Builder_Pattern;
using THenu.TinyHourseLib.DesignPattern.Factory_Method;
using System.Reflection;
using THenu.TinyHourseLib.DesignPattern;
using THenu.TinyHourseLib.EventAndDelegate.Weak_Reference;

namespace THenu.TinyHourseLib
{
    public partial class FrmHenuConsole : Form
    {
        /// <summary>
        /// 构造输入输出流
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        public FrmHenuConsole(Stream input, Stream output)
            : this()
        {


            FuncationCallRedictConsole(
            THenu.TinyHourseLib.DesignPattern.Specification_Pattern.Example.BeautyGirl.WhoIsZhengBingBing);

            FuncationCallRedictConsole(
            SmartBot.Singleton.CreateYourPeronalFriend);


            FuncationCallRedictConsole(
            THenu.TinyHourseLib.DesignPattern.Builder_Pattern.ActionBuilderPattern.PatternShow);


            FuncationCallRedictConsole(FactoryDisplay.PatternShow);

 

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="output"></param>
        /// <param name="sr"></param>
        private void StreamFlush(Stream output, StreamReader sr)
        {
            output.Flush();
            output.Seek(0, SeekOrigin.Begin);
            rtbOutPut.Text = sr.ReadToEnd();
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmHenuConsole()
        {
            InitializeComponent();

        }
        /// <summary>
        /// Enter 键发送指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rtbInput_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

            }
        }
        private bool ISRespond = false;
        /// <summary>
        /// 加载处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmHenuConsole_Load(object sender, EventArgs e)
        {
            try
            {
                Assembly assembly = Assembly.Load("THenu.TinyHourseLib.DesignPattern");
                List<Type> list = new List<Type>();

                //// 正常
                //foreach (var item in assembly.GetTypes())
                //{
                //    if (item.GetInterface("THenu.TinyHourseLib.DesignPattern.IPatternDemonstrate", true) != null)
                //    {
                //        list.Add(item);
                //    }
                //}
                //// 分组并排序
                //list = list.OrderBy(p => p.Namespace).ThenBy(p => p.Name).ToList();

                // 使用LINQ获取分组和排序
                Type[] typeAssembly = assembly.GetTypes();
                var itemSeq = from types in typeAssembly
                              where types.GetInterface("THenu.TinyHourseLib.DesignPattern.IPatternDemonstrate", true) != null
                              orderby types.Namespace, types.Name
                              select types;

                cmbDesignPatternList.DisplayMember = "Name";
                cmbDesignPatternList.DataSource = itemSeq.ToArray();

                // 打开响应
                ISRespond = true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 显示调用情况
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbDesignPatternList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbDesignPatternList.SelectedItem is Type && ISRespond)
                {
                    Type patternName = cmbDesignPatternList.SelectedItem as Type;
                    object objPattern = Activator.CreateInstance(patternName);


                    RedirectConsoleLines((IPatternDemonstrate)objPattern);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 重定向输出流
        /// </summary>
        /// <param name="displayClient"></param>
        private void RedirectConsoleLines(IPatternDemonstrate objPattern)
        {

            IPatternDemonstrate displayClient = objPattern as IPatternDemonstrate;
            rtbDescription.Text = displayClient.PatternDescription();

            /// <summary>
            /// 重定向输入输出流
            /// </summary>
            using (MemoryStream msConsoleOut = new MemoryStream())
            {
                StreamWriter swStandardOutput = new StreamWriter(msConsoleOut, Encoding.Unicode);
                swStandardOutput.AutoFlush = true;
                Console.SetOut(swStandardOutput);

                Console.WriteLine("====================   StructuralCode  ====================");
                displayClient.StructuralCode();
                Console.WriteLine("\r\n====================  RealWorldExample ====================");
                displayClient.RealWorldExample();

                // 将输出显示到面板
                StreamReader sr = new StreamReader(msConsoleOut, Encoding.UTF8);
                msConsoleOut.Seek(0, SeekOrigin.Begin);
                rtbOutPut.Text = sr.ReadToEnd();

                // 释放资源
                msConsoleOut.Close();
                msConsoleOut.Dispose();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbDesignPatternList_Format(object sender, ListControlConvertEventArgs e)
        {
            if (e.ListItem is Type)
            {
                e.Value = (e.ListItem as Type).Name.Replace("Pattern", string.Empty);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string filePath = "D:\\zbb.log";
            using (File.Create(filePath)) { }
            FileInfo logFile = new FileInfo(filePath);

            using (BinaryWriter logWrite = new BinaryWriter(logFile.OpenWrite(), Encoding.Default))
            {
                //byte[] content = System.Text.Encoding.Default.GetBytes("<name>0324-987 阿狸的裤衩</name>");
                //logWrite.Write(content, 0, content.Length);
                string contentstring = "<name>河南";

                logWrite.Write(contentstring);
                logWrite.Close();
            }

            using (BinaryReader brLog = new BinaryReader(logFile.OpenRead(), Encoding.Default))
            {
                byte[] content = new byte[brLog.BaseStream.Length];
                int length = brLog.Read(content, 0, content.Length);
                brLog.BaseStream.Seek(0, SeekOrigin.Begin);
                string str = brLog.ReadString();
                rtbInput.Text = str;
            }

        }
        /// <summary>
        /// 调用方法将结果输出
        /// </summary>
        /// <param name="fun"></param>
        private void FuncationCallRedictConsole(Action fun)
        {
            /// <summary>
            /// 重定向输入输出流
            /// </summary>
            using (MemoryStream msConsoleOut = new MemoryStream())
            {
                StreamWriter swStandardOutput = new StreamWriter(msConsoleOut, Encoding.Unicode);
                swStandardOutput.AutoFlush = true;
                Console.SetOut(swStandardOutput);

                Console.WriteLine("====================  Begin " + fun.Method.Name + " Call====================");
                fun();
                Console.WriteLine("\r\n====================  End " + fun.Method.Name + " Call====================");

                // 将输出显示到面板
                StreamReader sr = new StreamReader(msConsoleOut, Encoding.UTF8);
                msConsoleOut.Seek(0, SeekOrigin.Begin);
                rtbOutPut.Text = sr.ReadToEnd();

                // 释放资源
                msConsoleOut.Close();
                msConsoleOut.Dispose();
            }
        }

        private void BtnWeekReference_Click(object sender, EventArgs e)
        {
            FuncationCallRedictConsole(DisposableCache.DiaplayMain);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                form1 = new Form1();
                form1.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Dispose();

        }
        /// <summary>
        /// 检查防护非法的浮点数【如果有多个小数点，截取到第二个小数点前】
        /// 例如：出现 0.01.00 格式的数值 截除后面的 .00
        /// MiaoShuaitao 2014-08-26 16:23:56
        /// </summary>
        /// <param name="strValue"></param>
        private static string CheckFloatValueString(string strValue)
        {
            if (!strValue.Contains("."))
                return strValue;
            // 出现 0.01.00 格式的配置数值 截除后面的 .00 ★
            int spotFirst = strValue.IndexOf('.');
            int spotSecond = strValue.Substring(spotFirst + 1).IndexOf('.');
            // 截取到第二个小数点前
            if (spotSecond > -1)
            {
                strValue = strValue.Substring(0, spotFirst + 1 + spotSecond);
            }
            return strValue;
        }

        public Form1 form1 { get; set; }
    }
}
